package com.act.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class CarbonJdbcUtils {
	
	private static Log log = LogFactory.getLog(CarbonJdbcUtils.class);

	private static final String driverName = SystemConfig.getProperty("carbon.driver");
	private static final String url = SystemConfig.getProperty("carbon.url");
	private static final String user = SystemConfig.getProperty("carbon.user");
	private static final String password = SystemConfig.getProperty("carbon.password");
	
	public static Connection getConnection(){
		Connection conn = null;
		try {
			Class.forName(driverName);
			conn = DriverManager.getConnection(url,user,password);
		} catch (Exception e) {
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
		}
		return conn;
	}
	
	/**
	 * 释放数据库连接
	 * 
	 * @param conn
	 */
	public static void close(Connection conn) {
		if (conn == null) {
			return;
		}
		try {
			if (conn.isClosed()) {
				return;
			}
			conn.close();
		} catch (SQLException e) {
			if(log.isErrorEnabled()){
				log.error(e.getMessage(), e);
			}
		}
	}

	/**
	 * 关闭STMT
	 * @param stmt
	 */
	public static void close(Statement stmt) {
		if(stmt == null){
			return;
		}
		try {
			stmt.close();
		} catch (SQLException e) {
			if(log.isErrorEnabled()){
				log.error(e.getMessage(), e);
			}
		}
	}

	/**
	 * 关闭RS
	 * 
	 * @param rs
	 */
	public static void close(ResultSet rs) {
		if(rs == null){
			return;
		}
		try {
			rs.close();
		} catch (SQLException e) {
			if(log.isErrorEnabled()){
				log.error(e.getMessage(), e);
			}
		}
	}

	/**
	 * 关闭STMT和CONN
	 * @param stmt
	 * @param conn
	 */
	public static void close(Statement stmt, Connection conn) {
		close(stmt);
		close(conn);
	}

	/**
	 * 关闭RS、STMT和CONN
	 * 
	 * @param rs
	 * @param stmt
	 * @param conn
	 */
	public static void close(ResultSet rs, Statement stmt, Connection conn) {
		close(rs);
		close(stmt);
		close(conn);
	}
}
